package com.scorpio.redis.cachelock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisLock {
    private static final Logger log = LoggerFactory.getLogger(RedisLock.class);


    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 加锁
     *
     * @param lockKey
     * @param expire  超时/秒
     * @return
     */
    public boolean lock(String lockKey, int expire) {
        long recordTime = System.currentTimeMillis();
        long countDown = expire * 1000;
        while (true) {
            Boolean success = redisTemplate.opsForValue().setIfAbsent(lockKey, "");
            if (success) {
                redisTemplate.expire(lockKey, expire, TimeUnit.SECONDS);
                return true;
            }
            countDown -= Math.abs(System.currentTimeMillis() - recordTime);
            recordTime = System.currentTimeMillis();
            if (countDown <= 0) {
                //超时了
                return false;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
            }
        }
    }

    /**
     * 解锁
     *
     * @param lockKey
     */
    public void unlock(String lockKey) {
        try {
            redisTemplate.delete(lockKey);
        } catch (Exception e) {
            log.error("【redis分布式锁】解锁异常, {}", e);
        }
    }
}
